using System.Collections.Generic;
using System.Xml;
using UnityEngine;

/*
* Introduction：
* Creator：
*/

namespace HyxFrame.Core
{


    /// <summary>
    /// 
    /// </summary>
    public class ConfigManager : MonoSingleton<ConfigManager>
    {
        private static Dictionary<System.Type, ConfigLoadBase> m_configLoaders = new Dictionary<System.Type, ConfigLoadBase>();

        public T GetConfigManager<T>() where T : ConfigLoadBase
        {
            ConfigLoadBase loader = null;
            if (!m_configLoaders.TryGetValue(typeof(T), out loader))
                return null;

            return loader as T;
        }


        public static XmlDocument GetDocument(string path, string bundleName)
        {
            // TextAsset data = AssetLoadManager.LoadAsset<TextAsset>(bundleName, path);


            TextAsset data = null;


            if (data == null)
            {
                Debug.LogErrorFormat("Failed to load config from {0}", path);
                return null;
            }

            XmlDocument doc = new XmlDocument();
            try
            {
                doc.LoadXml(data.text);
            }
            catch (System.Exception ex)
            {
                Debug.LogErrorFormat("Failed to read xml from {0}. ({1})", path, ex.Message);
                return null;
            }

            return doc;
        }

        protected override void InitManager()
        {

        }

        private void Start()
        {
            Register();
        }

        protected override void OnDestroy()
        {
            UnRegister();
        }


        public void InitConfigDate<T>()
        {
            // 获取所有 ConfigLoadBase 类型的类
            var types = typeof(T).Assembly.GetTypes();
            for (int i = 0; i < types.Length; i++)
            {
                var type = types[i];
                if (type.IsSubclassOf(typeof(ConfigLoadBase)))
                {
                    var loader = System.Activator.CreateInstance(type) as ConfigLoadBase;
                    if (loader == null)
                        continue;

                    m_configLoaders.Add(types[i], loader);

                    loader.Load();
                }
            }
        }




        void Register()
        {

        }

        public void RefreshConfigManager<T>()
        {
            InitConfigDate<T>();
        }


        void UnRegister()
        {

        }

    }
}